package tech.aistar.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tech.aistar.entity.*;
import tech.aistar.entity.Collections;
import tech.aistar.entity.dynamic.Picture;
import tech.aistar.entity.massage.Massage;
import tech.aistar.entity.massage.MassageList;
import tech.aistar.entity.trading.Goods;
import tech.aistar.service.*;
import tech.aistar.util.HttpUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/info")
public class UserInfoController {
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IPetService petService;
    @Autowired
    private IUserRelationService userRelationService;
    @Autowired
    private ICollectionsService collectionsService;
    //密码
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //帖子
    @Autowired
    private IPostService postService;
//    @Autowired
//    private IComService comService;
    @Autowired
    private IPictureService pictureService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IMassageService massageService;


    @RequestMapping("/details")
    public String test(HttpServletResponse resp, HttpServletRequest req) {
        HttpSession ss=req.getSession();
        UserLogin userLogin= (UserLogin) ss.getAttribute("user");
        UserLogin userLogin1 = userLoginService.findByUserId(userLogin.getUserId());
        List<Pet> petlist = petService.findAllById(userLogin1.getId());
//        List<Post> postlist = postService.findAllPostByUserId(userLogin.getId());
        UserInfo userInfo = userInfoService.findById(userLogin1.getId());
        List<Com> comlist = userInfoService.findAllByUserId(userLogin1.getId());
        List<String> Titlelist = new ArrayList<>();
        for (Com c:comlist){
            String t = postService.findPostByPostId(c.getPostId()).getTitle();
            Titlelist.add(t);
        }
        req.getSession().setAttribute("user", userLogin1);
        req.getSession().setAttribute("info", userInfo);
        req.setAttribute("petlist", petlist);
//        采用流
//        req.setAttribute("postlist", postlist);
        req.setAttribute("comlist",comlist);
        req.setAttribute("title",Titlelist);
        return "/person/person";
    }

    //帖子
    @GetMapping("/postlist")
    @ResponseBody
    public List<Post> testpost(Integer id){
        List<Post> postlist = postService.findAllPostByUserId(id);
        return postlist;
    }
    //宠物秀
    @GetMapping("/com")
    @ResponseBody
    public Map<List<String>,List<Com>> testCom(Integer id){
        Map<List<String>,List<Com>> map = new HashMap<>();
        List<Com> comlist = userInfoService.findAllByUserId(id);
        List<String> Titlelist = new ArrayList<>();
        for (Com c:comlist){
            String t = postService.findPostByPostId(c.getPostId()).getTitle();
            Titlelist.add(t);
        }
        map.put(Titlelist,comlist);
        return map;
    }

    //动态
    @GetMapping("/piclist")
    @ResponseBody
    public List<Picture> testpic(Integer id){
        List<Picture> piclist = pictureService.findByUserId(id);
        return piclist;
    }

    //代理重定向到安全页面(带最新的数据)
    @RequestMapping("/agent")
    public String tests(HttpServletResponse resp, HttpServletRequest req) {
        HttpSession ss=req.getSession();
        UserLogin userLogin= (UserLogin) ss.getAttribute("user");
        UserLogin userLogin1 = userLoginService.findByUserId(userLogin.getUserId());
        UserInfo userInfo = userInfoService.findById(userLogin1.getId());
        List<Pet> petlist = petService.findAllById(userLogin1.getId());

//        ss.setAttrabite("CyList",null);
        ss.setAttribute("user",null);
        ss.setAttribute("info",null);
        req.getSession().setAttribute("user", userLogin1);
        req.getSession().setAttribute("info", userInfo);
        req.setAttribute("petlist", petlist);
        return "/person/safety";
    }

    //跳到他的个人中心
    @GetMapping("/data/{info}")
    public String test01(@PathVariable("info") Integer info, Model model) {
        if (info == 1) {
            //添加宠物  数据加入
            List<Pettype> addtype = petService.findAll();
            model.addAttribute("plist", addtype);
        }
//        UserInfo userInfo = userInfoService.findById()
        return "/person/data";
    }

    //谁的关注
//    @GetMapping("/focu/{id}/{pageNum}/{pageSize}")
    @RequestMapping("/focu")
    public String testFouc(Integer id, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "4") Integer pageSize, Model model) {
        //找他关注的集合(分页)
        Map<PageInfo<UserRelation>, List<UserInfo>> focumap = userRelationService.findFoucNum(id, pageNum, pageSize);
        Set<PageInfo<UserRelation>> set = focumap.keySet();
        for (PageInfo<UserRelation> focuPage : set) {
            System.out.println(focuPage);
            List<UserInfo> focuInfo = focumap.get(focuPage);
            model.addAttribute("focuPage", focuPage);
            model.addAttribute("focuInfo", focuInfo);
        }
//        //粉丝
//        Map<PageInfo<UserRelation>,List<UserInfo>> fansmap = userRelationService.findFansNum(id,pageNum,pageSize);
//        Set<PageInfo<UserRelation>> set01 =fansmap.keySet();
//        for(PageInfo<UserRelation> fansPage:set01){
//            System.out.println(fansPage);
//            List<UserInfo> fansInfo = fansmap.get(fansPage);
//            model.addAttribute("fansPage",fansPage);
//            model.addAttribute("fansInfo",fansInfo);
//        }
        //跳转到关注页面(ajax)
        return "/person/focupage";
        //跳转到粉丝后台
//        return "forward:/info/fans";
    }

    @GetMapping("/personal/{id}")
    public String testPersonal(Model model,@PathVariable("id")Integer id){
        UserInfo otherInfo = userInfoService.findById(id);
        List<Pet> petlist = petService.findAllById(id);
        List<Post> postlist = postService.findAllPostByUserId(id);
        List<Com> comlist = userInfoService.findAllByUserId(id);
        List<String> Titlelist = new ArrayList<>();
        for (Com c:comlist){
            String t = postService.findPostByPostId(c.getPostId()).getTitle();
            Titlelist.add(t);
        }
        model.addAttribute("otherInfo",otherInfo);
        model.addAttribute("petlist",petlist);
        model.addAttribute("postlist",postlist);
        model.addAttribute("comlist",comlist);
        model.addAttribute("title",Titlelist);
        return "/person/otherPerson";
    }

//粉丝异步请求到这里
    @RequestMapping("/fans")
    public String testFans(Integer id, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "2") Integer pageSize,Model model){
        //粉丝
        Map<PageInfo<UserRelation>,List<UserInfo>> fansmap = userRelationService.findFansNum(id,pageNum,pageSize);
        Set<PageInfo<UserRelation>> set01 =fansmap.keySet();
        PageInfo<UserRelation> re = null;
        for(PageInfo<UserRelation> fansPage:set01){
            //System.out.println(fansPage);
            List<UserInfo> fansInfo = fansmap.get(fansPage);
            model.addAttribute("fansPage",fansPage);
            model.addAttribute("fansInfo",fansInfo);
            re = fansPage;
        }

        //判断关系
        List<Boolean>isBoth = new ArrayList<>();
        for(UserRelation ur : re.getList()){
            Boolean s = userRelationService.bothShip(ur.getId(),ur.getUserByid());
            isBoth.add(s);
        }
        model.addAttribute("isBoth",isBoth);
        //跳转到关注页面(ajax)
        return "/person/fanspage";
    }


    @RequestMapping("/focuson")
    public String pages(Model model){
        //先到主页面  在由主页面 通过 load 方法加载下面的方法  加载分页的数据页面
        model.addAttribute("flag",0);
        return "/person/focuson";
    }

    @RequestMapping("/otherFocuson")
    public String otherpage(Model model){
        //先到主页面  在由主页面 通过 load 方法加载下面的方法  加载分页的数据页面
        model.addAttribute("flag",1);

        return "/person/focuson";
    }

    @RequestMapping("/safety")
    public String safety(){
        return "/person/safety";
    }


    //验证用户的操作
//    @GetMapping("/detection")
//    public @ResponseBody Result checkUser(UserLogin userLogin){
//        UserLogin ul = userLoginService.findByUserId(userLogin.getUserId());
//        System.out.println(ul);
//        if(null != ul && ul.getUserPassword().trim().equals(userLogin.getUserPassword().trim())){
//            System.out.println("-------------------------------------------------------------------");
//            return new Result(CodeStatus.OK,true,"验证用户成功",ul);
//
//        }
//        return new Result(CodeStatus.ERROR,false,"验证用户失败",ul);
//    }



    //验证密码  需要    @Autowired
    @GetMapping("/detection")
    public  @ResponseBody Boolean checkUser(UserLogin userLogin){
        UserLogin ul = userLoginService.findByUserId(userLogin.getUserId());
        //System.out.println(ul);
        if(null != ul && passwordEncoder.matches(userLogin.getUserPassword(),ul.getUserPassword())){
//        if(null != ul && userLogin.getUserPassword().equals(ul.getUserPassword())){
            //System.out.println("-------------------------------------------------------------------");
            return true;
        }
        return false;
    }

    //验证手机号
    @GetMapping("/isPhone")
    public  @ResponseBody Boolean checkPhone(String uPhone){
        List<String> phones = userInfoService.findPhones();
        for(String p:phones) {
            if (null != p && p.equals(uPhone)) {
                System.out.println("-------------------------------------------------------------------");
                return false;
            }
        }
        return true;
    }
    //验证码
    @PostMapping("/yzm")
    public  @ResponseBody Boolean checkYZM(HttpServletRequest req,String yzm){
        //验证码校验
        HttpSession ss=req.getSession();
        String autocode= (String) ss.getAttribute("autocode");
        System.out.println(autocode);
        if (autocode.equals(yzm)){
            return true;
        }else {
            return false;
        }
    }

    //验证邮箱(是否绑定其他用户)
    @GetMapping("/isEmail")
    public  @ResponseBody Boolean checkEmail(String uEmail){
        List<String> email = userInfoService.findEmail();
        for(String e:email) {
            if (null != e && e.equals(uEmail)) {
                System.out.println("-------------------------------------------------------------------");
                return false;
            }
        }
        return true;
    }

    //验证身份证(是否绑定其他用户)
    @GetMapping("/isCard/{numder}")
    public  @ResponseBody Boolean checkCard(@PathVariable("numder") String numder){
        List<String> cards = userLoginService.findCards();
        for(String c:cards) {
            if (null != c && c.equals(numder)) {
                System.out.println("-------------------------------------------------------------------");
                return false;
            }
        }
        return true;
    }

    //验证身份是否真实存在
    @GetMapping("/cradTrue")
    public  @ResponseBody Boolean CradTrue(String name,String numder){
        System.out.println("名字 +"+ name+"     号码"+numder);
        String host = "http://idcard.market.alicloudapi.com";
        String path = "/lianzhuo/idcard";
        String method = "GET";
        String appcode = "31df3b920aa24321b57a911326bd095f";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
//        querys.put("cardno", "370703198111300338");
//        querys.put("name", "郭德昌");
        querys.put("cardno", numder);
        querys.put("name", name);

        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            String resBody = EntityUtils.toString(response.getEntity());
            System.out.println(resBody);
            JSONObject jsonObject = JSONObject.parseObject(resBody);
            JSONObject person = jsonObject.getJSONObject("resp");
            String code = null;
            if (person!=null) {
                //System.out.println(jsonArray.get(i));
                code = person.getString("code");
                System.out.println(code);
            }
            if("0".equals(code)){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//            //获取response的body
//            //System.out.println(EntityUtils.toString(response.getEntity()));
        return false;
    }


    @RequestMapping("/collect/{id}")
    public String collect(@PathVariable("id") Integer id,Model model){
        //先到主页面  在由主页面 通过 load 方法加载下面的方法  加载分页的数据页面
        List<Collections> coll = collectionsService.findByPost(id);
        List<Post> collpost = new ArrayList<>();
        for (Collections c:coll){
            Post p = postService.findPostByPostId(c.getKindId());
            collpost.add(p);
        }
        model.addAttribute("collpost",collpost);
        return "/person/collect";
    }
    @RequestMapping("/collect")
    public String collects(){
        return "/person/collect";
    }

    @RequestMapping("/coll")
    public String collpage(Integer id,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "4") Integer pageSize,Model model){
        Integer count = collectionsService.findById(id);
        PageInfo<Collections>goodList = collectionsService.findByGood(id,pageNum,pageSize);
        model.addAttribute("count",count);
        List<Goods> goodsList = new ArrayList<>();
        for (Collections c:goodList.getList()){
            Goods g = collectionsService.findByGood(c.getKindId());
            goodsList.add(g);
        }
        //你要遍历的商品数据
        model.addAttribute("goodsList",goodsList);
//        List<Collections> collpost = collectionsService.findByPost(id);
//        model.addAttribute("collpost",collpost);
        //这个是分页的
        model.addAttribute("goodList",goodList);
        return "/person/collpage";
    }

    @RequestMapping("/massage")
    public String testmassage(){
        return "/massage/massage";
    }

    @RequestMapping("/index")
    public String testindex(HttpServletRequest req,HttpServletResponse resp,Model model){

        Integer userCount = userLoginService.findByCount();
        model.addAttribute("userCount",userCount);
        List<Picture> pic = pictureService.findAll();
        Integer picCount = pic.size();
        model.addAttribute("picCount",picCount);
        List<Post> list = postService.findAllPost1();
        Integer postCount = list.size();
        model.addAttribute("postCount",postCount);
//        首页帖子
        List<Post> post01 = userInfoService.findByThemeId(1);
        model.addAttribute("post01",post01);

        List<Post> post02 = userInfoService.findByThemeId(2);
        model.addAttribute("post02",post02);

        List<Post> post03 = userInfoService.findByThemeId(3);
        model.addAttribute("post03",post03);

        List<Post> post04 = userInfoService.findByThemeId(4);
        model.addAttribute("post04",post04);

        //消息
        HttpSession ss=req.getSession();
        UserLogin userLogin= (UserLogin) ss.getAttribute("user");
        List<Massage> UnreadPost = massageService.findUnReadPost(userLogin.getId());
        List<Massage> UnreadCom = massageService.findUnReadCom(userLogin.getId());
//        UnreadPost.forEach(System.out::println);
//        model.addAttribute("massNum",UnreadPost.size());
        req.getSession().setAttribute("massNum", UnreadPost.size()+UnreadCom.size());

        return "forward:/top/topn";
    }

    //首页帖子
//    @GetMapping("/indexPost")
//    @ResponseBody
//    public List<Post> test01(Integer themeId){
//        List<Post> post01 = userInfoService.findByThemeId(themeId);
//        return post01;
//    }


}
